package lucene.server.cdc.mysql.util;

import lucene.server.cdc.mysql.model.BinlogPosition;
import lucene.server.common.dbmeta.DialectUtil;
import lucene.server.common.utils.DatabaseUtil;

import java.sql.Connection;
import java.util.*;

public class BinlogUtil {

    public static BinlogPosition getIniBinlogPosition(Properties properties, BinlogPosition storedBinlogPosition){
        Map<String, Object> masterBinlog = findMaxLogName(properties);

        if (masterBinlog == null){
            return storedBinlogPosition;
        }
        String masterBinlogName = (String) masterBinlog.get("Log_name");
        long masterBinlogPosition = Long.parseLong(masterBinlog.get("File_size").toString());
        if (storedBinlogPosition ==null || storedBinlogPosition.getBinlogName() == null){
            return new BinlogPosition(masterBinlogName,masterBinlogPosition);
        }
        if (!storedBinlogPosition.getBinlogName().equals(masterBinlogName)){
            return new BinlogPosition(storedBinlogPosition.getBinlogName(), storedBinlogPosition.getPosition());
        }else{
            if (storedBinlogPosition.getPosition() > masterBinlogPosition){
                return new BinlogPosition(storedBinlogPosition.getBinlogName(),masterBinlogPosition);
            }else{
                return new BinlogPosition(storedBinlogPosition.getBinlogName(),storedBinlogPosition.getPosition());
            }
        }

    }

    public static Map<String, Object> findMaxLogName(Properties properties){
        List<Map<String, Object>> list = getBinlogList(properties);
        if (list == null || list.size() == 0){
            return null;
        }
        return list.get(list.size() - 1);
    }
    public static List<Map<String, Object>> getBinlogList(Properties properties){
        Connection connection = null;
        try{
            connection = DialectUtil.getConnection(properties);
            List<Map<String, Object>> list = DatabaseUtil.executeSelectToList(connection,"SHOW BINARY LOGS;");
            if (list != null && list.size() > 0){
                return list;
            }
        }catch (Exception e){

        }finally {
            DatabaseUtil.close(connection);
        }
        return null;
    }


    public static  boolean isLatest(Properties properties,String binlogName,Long position){

        return false;

    }


}
